# -*- codeing:UTF-8 -*_
'''
@Date   :2023/12/3
@Time   :12:43
@Author :RussellZhou
@Desc   :sgs节气封面获取
'''

# /usr/bin python
# coding = utf-8


from bs4 import BeautifulSoup
import requests
import os
# 初始化

for type in range(1,4):
    file_path=f'img/{type}/'
    if os.path.exists(file_path):
        if len(os.listdir(file_path))==0:
            #文件夹为空，使用os.rmdir()删除
            os.rmdir(file_path)
    else:
        os.makedirs(file_path)
    for page in range(1,9):
        url = f"https://www.sanguosha.cn/pc/wallpaper.html?type={type}&page={page}"
        header = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36"}
        # 获取地址
        # 获取图片递归函数
        # 使用 requests模块获取响应对象
        res = requests.get(url, headers=header)
        # 更改编码格式
        res.encoding = "utf-8"
        html=res.text
        soup=BeautifulSoup(html,'html.parser')
        imgs_list=soup.findAll('img')
        imgUrlBase="https://www.sanguosha.cn/"
        try:
            for i in range(5,17):
                imgName=imgs_list[i]['alt']
                imgUrl=imgs_list[i]['src']
                imgFullUrl=imgUrlBase+imgUrl
                img_data=requests.get(url=imgFullUrl,headers=header).content
                img_path=file_path+str(imgName)+'.jpeg'
                with open(img_path, 'wb') as f:
                    print(f"{imgName}正在下载中")
                    f.write(img_data)
        except IndexError as e:
            print("索引超出范围")
            continue